package com.miku.blog.utils;

import com.miku.blog.domain.pojo.LoginUser;
import com.miku.blog.domain.UserAuth;
import com.miku.blog.eume.HttpStatusEnum;
import com.miku.blog.exception.SystemException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * @author shkstart
 * @create ${}YEAR-05-26 6:25
 */
public class SecurityUtils {

    public static UserAuth getUserAuth(){
        return getLoginUser().getUserAuth();
    }

    public static LoginUser getLoginUser(){
        Object principal = getAuthentication().getPrincipal();
        if (String.class.isAssignableFrom(principal.getClass())){
            throw new SystemException(HttpStatusEnum.NEED_LOGIN_AGAIN);
        }
        return  (LoginUser) principal;
    }

    public static Authentication getAuthentication(){
        Authentication authentication = getSecurityContext().getAuthentication();
        if (Objects.isNull(authentication)){
            throw new SystemException(HttpStatusEnum.NEED_LOGIN_AGAIN);
        }
        return authentication;
    }

    public static SecurityContext getSecurityContext(){
        return SecurityContextHolder.getContext();
    }

}
